﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalR.Controllers
{

    public class OnlineClient
    {
        public string NickName { get; set; }

        public string Avatar { get; set; }
        public string Email { get; internal set; }
        public string Mobile { get; internal set; }
    }

    //[HubName()] 和  [HubMethodName()]，可以自行指定Hub类和自定义方法的名称，指定为什么，前端调用就用什么
    public class ChatHub : Hub
    {
        private readonly static List<string> _connections = new List<string>();
        public void SendMsg(string message, string connectionid)
        {

            if (connectionid != null)
            {
                //调用客户端方法
                // Clients.Clients

                Clients.Client(connectionid).SendAsync("ID:" + connectionid, message + " 时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                Clients.All.SendAsync("ID:" + connectionid, message + " 时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }

        public async Task SendMessage(string user, string message)
        {
           // Clients.us
            await Clients.All.SendAsync("ReceiveMessage", user, DateTime.Now.ToString("yyyy-mm-dd HH:MM:ss"), message);
        }

        public override async Task OnConnectedAsync()
        {
            var http = Context.GetHttpContext();
            _connections.Add(Context.ConnectionId);

            await base.OnConnectedAsync();
            //  await Groups.AddToGroupAsync(Context.ConnectionId, ChatName);
            // await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用户{client.NickName}加入了群聊");
            //await Clients.Client(Context.ConnectionId).SendAsync("system", $"成功加入{ChatName}");
            await Clients.All.SendAsync("OnConnected", $@"{Context.ConnectionId}上线了");
        }
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);

            _connections.Remove(Context.ConnectionId);
            await Clients.All.SendAsync("OnDisconnected", $@"{Context.ConnectionId}断线了");
        }
    }
}
